package top.lbqaq.service;

import top.lbqaq.dao.BaseDao;
import top.lbqaq.dao.UserDao;
import top.lbqaq.error.BaseException;
import top.lbqaq.error.DuplicateKeyException;
import top.lbqaq.pojo.User;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author luoboQAQ
 * @Date 2021/11/21
 */
public class UserService {

    private final UserDao userDao = new UserDao();

    public User login(String username, String password) {
        Connection connection = null;
        User user = null;

        connection = BaseDao.getConnection();
        try {
            user = userDao.getLoginUser(connection, username);
            if (user == null) {
                return null;
            }
            if (user.getPassword().equals(password)) {
                return user;
            } else {
                return null;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public Boolean register(User user) throws BaseException {
        Connection connection = null;
        connection = BaseDao.getConnection();
        int end = 0;
        // 注册的都是游客
        user.setRoleId(3L);
        try {
            if (userDao.getLoginUser(connection, user.getUsername()) != null) {
                throw new DuplicateKeyException("重复的用户名");
            }
            end = userDao.insertUser(connection, user);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return end > 0;
    }
}
